package com.ls.pattern.observer.mouse.core;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * 被观察者抽象
 *
 * @author 挥之以墨
 */
public class EventContext {

    protected Map<String, Event> events = new HashMap<>();

    public void addListener(String eventType, EventListener listener, Method callback) {
        events.put(eventType, new Event(listener, callback));
    }

    public void addListener(String eventType, EventListener listener) {
        try {
            addListener(eventType, listener, listener.getClass().getMethod("on" + toUpperFirstCase(eventType), Event.class));
        } catch (NoSuchMethodException e) {
            System.out.println("事件：" + eventType + "不存在");
        }
    }

    private void trigger(Event event) {
        event.setSource(this);
        event.setTime(System.currentTimeMillis());

        if (event.getCallback() != null) {
            try {
                event.getCallback().invoke(event.getListener(), event);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    protected void trigger(String trigger) {
        if (!this.events.containsKey(trigger)) {
            System.out.println("事件：" + trigger + "未注册");
            return;
        }

        trigger(this.events.get(trigger).setTrigger(trigger));
    }


    private String toUpperFirstCase(String eventType) {
        char[] chars = eventType.toCharArray();
        chars[0] -= 32;
        return String.valueOf(chars);
    }

}
